<template>
  <el-card class="address-card">
    <template #header>
      <div class="card-header">
        <span><el-icon><Location /></el-icon> 地址信息</span>
        <div class="header-actions">
          <el-button type="primary" @click="showEditDialog">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
        </div>
      </div>
    </template>
    
    <el-table 
      :data="addressList" 
      style="width: 100%" 
      v-loading="loading"
      empty-text="暂无数据"
    >
      <el-table-column prop="contact" label="联系人" width="120" />
      <el-table-column prop="mobile" label="手机号" width="120" />
      <el-table-column label="所在地区" min-width="200">
        <template #default="scope">
          {{ getRegionNames(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="street" label="详细地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="notes" label="备注" min-width="150" show-overflow-tooltip />
      <el-table-column prop="isDefault" label="是否默认" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isDefault === 1 ? 'success' : 'info'">
            {{ scope.row.isDefault === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            link
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button 
            type="danger" 
            link
            @click="handleDelete(scope.row.id)"
          >删除</el-button>
          <el-button 
            v-if="scope.row.isDefault !== 1"
            type="success" 
            link
            @click="handleSetDefault(scope.row.id)"
          >设置默认</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑地址信息对话框 -->
    <el-dialog
      v-model="editAddressDialogVisible"
      :title="editAddressForm.id ? '编辑地址信息' : '新增地址信息'"
      width="500px"
    >
      <el-form :model="editAddressForm" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="editAddressForm.contact" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editAddressForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="selectedRegion"
            :options="regionOptions"
            :props="{
              value: 'value',
              label: 'label',
              children: 'children'
            }"
            placeholder="请选择所在地区"
            clearable
            @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="street">
          <el-input v-model="editAddressForm.street" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="editAddressForm.notes" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-switch v-model="editAddressForm.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editAddressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Location, Edit, Delete, Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { getMyAddresses, updateAddress, createAddress, deleteAddress, setDefaultAddress, type AddressDTO } from '@/api/address'
import { getFullAreaData, getAreaName } from '@/utils/areaData'

const addressList = ref<AddressDTO[]>([])
const loading = ref(false)
const editAddressDialogVisible = ref(false)
const formRef = ref<FormInstance>()
const selectedRegion = ref<string[]>([])
const regionOptions = ref(getFullAreaData())

const editAddressForm = ref<AddressDTO>({
  contact: '',
  mobile: '',
  province: '',
  city: '',
  town: '',
  street: '',
  isDefault: 0,
  notes: ''
})

// 表单验证规则
const rules = {
  contact: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    // { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  street: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

// 获取地区名称
const getRegionNames = (address: AddressDTO) => {
  const province = getAreaName(address.province)
  const city = getAreaName(address.city)
  const town = getAreaName(address.town)
  return `${province}${city}${town}`
}

// 处理地区选择变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length === 3) {
    editAddressForm.value.province = value[0]
    editAddressForm.value.city = value[1]
    editAddressForm.value.town = value[2]
  } else {
    editAddressForm.value.province = ''
    editAddressForm.value.city = ''
    editAddressForm.value.town = ''
  }
}

// 获取地址信息
const fetchAddressInfo = async () => {
  loading.value = true
  try {
    const res = await getMyAddresses()
    console.log('API Response:', res)
    
    // 使用类型断言处理响应数据
    const responseData = res as any
    
    // 确保数据存在且格式正确
    if (responseData?.data?.data) {
      addressList.value = responseData.data.data
    } else if (responseData?.data) {
      // 兼容不同的响应格式
      addressList.value = responseData.data
    } else {
      addressList.value = []
    }
  } catch (error) {
    console.error('Error fetching address list:', error)
    ElMessage.error('获取地址列表失败')
    addressList.value = []
  } finally {
    loading.value = false
  }
}

const showEditDialog = () => {
  editAddressForm.value = {
    contact: '',
    mobile: '',
    province: '',
    city: '',
    town: '',
    street: '',
    isDefault: 0,
    notes: ''
  }
  selectedRegion.value = []
  editAddressDialogVisible.value = true
}

const handleEdit = (row: AddressDTO) => {
  editAddressForm.value = { ...row }
  selectedRegion.value = [
    row.province,
    row.city,
    row.town
  ]
  editAddressDialogVisible.value = true
}

const saveAddress = async () => {
  if (!formRef.value) return
  
  // 验证地区是否已选择
  if (!selectedRegion.value || selectedRegion.value.length !== 3) {
    ElMessage.warning('请选择完整的所在地区')
    return
  }
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (editAddressForm.value.id) {
          // 更新地址
          await updateAddress(Number(editAddressForm.value.id), editAddressForm.value)
          ElMessage.success('地址信息更新成功')
        } else {
          // 新增地址
          await createAddress(editAddressForm.value)
          ElMessage.success('地址信息添加成功')
        }
        editAddressDialogVisible.value = false
        await fetchAddressInfo() // 重新获取地址信息
      } catch (error) {
        console.error('保存地址失败：', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 删除地址
const handleDelete = async (id: string | number) => {
  try {
    await ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteAddress(Number(id))
    ElMessage.success('地址删除成功')
    await fetchAddressInfo() // 重新获取地址信息
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 设置默认地址
const handleSetDefault = async (id: string | number) => {
  try {
    await setDefaultAddress(Number(id))
    ElMessage.success('设置默认地址成功')
    await fetchAddressInfo() // 重新获取地址信息
  } catch (error) {
    console.error('设置默认地址失败：', error)
    ElMessage.error('设置失败')
  }
}

// 在 script setup 部分添加日期格式化函数
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  fetchAddressInfo()
})

// 暴露方法给父组件
defineExpose({
  addressList,
  fetchAddressInfo
})
</script>

<style scoped>
.address-card {
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

:deep(.el-descriptions__label) {
  width: 100px;
}

:deep(.el-cascader) {
  width: 100%;
}
</style> 